module Pagination
  module ActiveRecordRelationExtension

    def entry_name(options = {})
      default = options[:count] == 1 ? model_name.human : model_name.human.pluralize
      model_name.human(options.reverse_merge(default: default))
    end

    #设置每页件数
    def per(num)
      # @_per = (num || default_per_page).to_i
      if (limit_v = num.to_i) < 0 || !(/^\d/ =~ num.to_s)
        self
      elsif limit_v.zero?
        limit(limit_v)
      else
        limit(limit_v).offset(offset_value * limit_v / limit_value)
      end
    end

    #总件数
    def total_count(column_name = :all)
      return @total_count if defined?(@total_count) && @total_count

      #去掉sql的limit, offset, order语句
      c = except(:limit, :offset, :order)
      c = c.except(:includes) unless references_eager_loaded_tables?

      @total_count =
          if c.group_values.any? #有group by语句时特殊处理
            #SELECT COUNT(*) FROM (SELECT 1 FROM `blogs` GROUP BY `blogs`.`published`) subquery
            c.model.from(c.except(:select).select('1')).count
          else
            c.count(column_name)
          end
    end

    #重写重置
    def reset
      @total_count = nil
      super
    end

    #总页数
    def total_pages
      #总件数 / 每页件数，再取大于它的最小整数
      (total_count.to_f / limit_value).ceil
    end

    #当前页数
    def current_page
      offset_value / limit_value + 1
    end

    #下一页的页码
    def next_page
      return if last_page? || out_of_range?
      current_page + 1
    end

    #上一页的页码
    def prev_page
      return if first_page? || out_of_range?
      current_page - 1
    end

    #是否第一页
    def first_page?
      current_page == 1
    end

    #是否最后一页
    def last_page?
      current_page == total_pages
    end

    #是否超出分页范围
    def out_of_range?
      c_page = current_page
      c_page < 1 || c_page > total_pages
    end
  end
end